package loading

import (
	"fmt"
	"time"
)

type Loading struct {
	frames []string
	active bool
	done   chan bool
}

// New 创建一个新的 Loading 实例
func New() *Loading {
	return &Loading{
		frames: []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"},
		done:   make(chan bool),
	}
}

// SetFrames 自定义动画帧
/* func (l *Loading) SetFrames(frames []string) {
	l.frames = frames
}

// SetMessage 自定义显示消息
func (l *Loading) SetMessage(msg string) {
	l.message = msg
} */

// Start 启动 loading 动画
func (l *Loading) Start() {
	l.active = true
	go func() {
		i := 0
		for {
			select {
			case <-l.done:
				// fmt.Printf("\r%s\n", "Done!      ")
				fmt.Printf("\r%s", " ")
				return
			default:
				if l.active {
					fmt.Printf("\r%s ", l.frames[i])
					i = (i + 1) % len(l.frames)
					time.Sleep(100 * time.Millisecond)
				}
			}
		}
	}()
}

// Stop 停止 loading 动画
func (l *Loading) Stop() {
	if l.active {
		l.active = false
		l.done <- true
	}
}

// WithLoading 高阶函数，包装需要显示 loading 的操作
func WithLoading(task func()) {
	l := New()
	l.Start()
	defer l.Stop()

	task()
}
